import 'dart:math';

import 'package:fancy_shimmer_image/fancy_shimmer_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:qianyi/entity/home/AlbumEntity.dart';
import 'package:qianyi/entity/home/album_detail_list_entity.dart';
import 'package:qianyi/entity/message/inner/CommentEntityInner.dart';
import 'package:qianyi/entity/message/inner/FollowEntity.dart';
import 'package:qianyi/entity/message/inner/LikeAndCollectEntity.dart';
import 'package:qianyi/network/http_manager.dart';
import 'package:qianyi/view_model/home/trend_view_model.dart';

import '../../../../controller/homeTabController.dart';
import '../../../../controller/imageDetailVideoController.dart';
import '../../../../entity/tags/Item.dart';
import '../../../../network/http_config.dart';
import '../../../../network/http_entity.dart';
import '../../../../state/token.dart';
import '../../../../ui/widget/custom_refresh.dart';
import '../../../../utils/throttle.dart';
import '../../../../view_model/home/AlbumDetailListModel.dart';
import '../../../../view_model/home/comment_view_model.dart';
import '../../../../view_model/home/tags/TagsDetailListModel.dart';
import '../../../../view_model/message/inner/comment_view_model.dart';
import '../../../../view_model/message/inner/follow_view_model.dart';
import '../../../../view_model/message/inner/like_and_collect_view_model.dart';
import '../../../../view_model/mine/album_view_model.dart';
import '../../../../wcao/ui/theme.dart';


class CommentScreen extends StatefulWidget {
  @override
  _LikeAndCollectScreenState createState() => _LikeAndCollectScreenState();
}

class _LikeAndCollectScreenState extends State<CommentScreen> {
  HomeTabController homeTabController = Get.find();
  CategoryItem? albumEntity;
  bool isFinish = false;
  List<String> images = [
    'https://example.com/image1.jpg', // 替换为实际图片链接
    'https://example.com/image2.jpg', // 替换为实际图片链接
    // 添加更多图片链接...
  ];
  ImageDetailVideoController imageDetailVideoController = Get.find<ImageDetailVideoController>();

  List<String> tabs = ["最新","最热"];
  @override
  void initState() {

    // TODO: implement initState
    super.initState();
    // getAlbumEntity();
  }
  getAlbumEntity() async {
    HudUtil.showBeautiful(context);
    Map<String,String> params1 = {
      "id":homeTabController.tagDetailId!,
    };

    HttpEntity httpEntity1 = await HttpManager.getInstance().request(url: '/platform/tag/getOneTag/',params: params1,method: Method.get) as HttpEntity;

    setState(() {
      albumEntity = CategoryItem.fromJson(httpEntity1.getOriData()['data']);
      this.isFinish = true;
    });
    HudUtil.dismiss();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: Text("评论记录")

      ),
      body: SafeArea(child: ChangeNotifierProvider(
        create: (context) => CommentInnerViewModel(),
        child: Consumer<CommentInnerViewModel>(
            builder: (context, viewModel, child) {

              return

                CustomRefresh(

                    isMaterialHeader:true,
                    controller: viewModel.refreshController,
                    enablePullUp: true,
                    enablePullDown: true,
                    onRefresh: () async {
                      viewModel.onRefresh();
                    },
                    onLoading: () async {
                      viewModel.onLoading();
                    },
                    child: ListView.builder(
                      itemCount: viewModel.datas.length,
                      itemBuilder: (BuildContext context, int index) {
                        CommentEntityInner item = viewModel.datas[index];
                        return GestureDetector(
                            onTap: () async {
                              HudUtil.showBeautiful(context);
                              imageDetailVideoController.imageDetailId.value = item.mid!;
                              await imageDetailVideoController.getImageVideoDetail();
                              // Loader.hide();
                              HudUtil.dismiss();
                              Get.toNamed("/ui/home/imageVideoDetail");
                            },
                            child: Card(
                              margin: EdgeInsets.all(8.0),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [

                                  Row(
                                    children: [
                                      ClipOval(
                                          child: FancyShimmerImage(imageUrl: '${item.avatar}',width: 40,height: 40,)
                                      )
                                      ,

                                      Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          Container(

                                              child: Text('${item.username}：',style: TextStyle(

                                              ),)
                                          )
                                          ,
                                          SizedBox(
                                            width: 200,
                                           child: Text(maxLines:2, "${item.content}"),
                                          ),
                                          Row(
                                            children: [
                                              Text("${DateFormat.Md().format(
                                                  DateTime.fromMillisecondsSinceEpoch(item.createDate!)
                                              )}-"),
                                              Text("${DateFormat.Hms().format(
                                                  DateTime.fromMillisecondsSinceEpoch(item.createDate!)
                                              )}")
                                            ],
                                          )

                                        ],
                                      )
                                    ],
                                  ),
                                  Flexible(child: Text('| ${item.replyContent==null?'':item.replyContent}',maxLines: 3,))
                                  ,
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                                    children: [

                                      FancyShimmerImage(imageUrl: '${item.cover}',height: 80,width:65,boxFit: BoxFit.cover,)
                                    ],
                                  )

                                ],
                              ),
                            )
                        )
                        ;
                      },
                    )
                );
            }),
      )),
    );
    ;
  }

  double getRandomHeight() {
    // 生成一个随机高度
    double height = Random().nextDouble() * (200 - 80) + 168;
    return   height ;
  }
  buildWateFall() {
    TokenController tokenController = Get.find();

    ImageDetailVideoController imageDetailVideoController = Get.find<ImageDetailVideoController>();
    return ChangeNotifierProvider(
      create: (context) => TagsDetailListModel(),
      child: Consumer<TagsDetailListModel>(
          builder: (context, viewModel, child) {
            ;
            return

              CustomRefresh(

                  isMaterialHeader:true,
                  controller: viewModel.refreshController,
                  enablePullUp: true,
                  enablePullDown: true,
                  onRefresh: () async {
                    viewModel.onRefresh();
                  },
                  onLoading: () async {
                    viewModel.onLoading();
                  },
                  child:MasonryGridView.count(
                    padding: EdgeInsets.all(0),
                    // 展示几列
                    crossAxisCount: 2,
                    // 元素总个数
                    itemCount: viewModel.datas.length,
                    // 单个子元素
                    itemBuilder: (BuildContext context, int index) {
                      TagItem trendEntity = viewModel.datas[index];
                      // var imgsUrl = jsonDecode(trendEntity.imgsUrl as String);
                      return GestureDetector(
                        onTap: () async {

                          HudUtil.showBeautiful(context);
                          String uid = await tokenController.getUid();
                          Map<String,dynamic> params = {
                            "mid":trendEntity!.id,
                            "uid": uid
                          };
                          HttpManager.getInstance().request(url: '/platform/browseRecord/addBrowseRecord',method: Method.post,params: params);
                          imageDetailVideoController.imageDetailId.value = trendEntity!.id!;
                          await imageDetailVideoController.getImageVideoDetail();
                          HudUtil.dismiss();
                          Get.toNamed("/ui/home/imageVideoDetail");

                        },
                        child: Card(
                          margin: EdgeInsets.all(1.5),

                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(4.0),
                            child:  Column(
                              children: [
                                FancyShimmerImage(
                                  height: getRandomHeight(),
                                  imageUrl: trendEntity.cover!,
                                ),

                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [

                                    Flexible(

                                      child: Text(
                                        trendEntity.content as String,maxLines: 2,softWrap: true, // 允许文本在超出最大行数时以省略号结束
                                        overflow: TextOverflow.ellipsis, style: TextStyle(fontWeight: FontWeight.w400),// 设置文本左对齐
                                      ),

                                    ),




                                  ],
                                )

                                ,
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    Row(
                                      children: [
                                        ClipOval(
                                            child: FancyShimmerImage(imageUrl: trendEntity.avatar as String,width: 20,height: 20,)
                                        ),

                                        Text(trendEntity.username as String),
                                      ],
                                    ),
                                    Row(
                                      children: [
                                        Icon(
                                          CupertinoIcons.heart,size: 14,
                                          color: Colors.grey,),
                                        Text(trendEntity.agreeCount as String)
                                      ],
                                    )
                                  ],
                                )

                              ],
                            ),
                          ),
                        ),
                      );
                    },

                    // 纵向元素间距
                    mainAxisSpacing: 0,
                    // 横向元素间距
                    crossAxisSpacing: 0,
                    //本身不滚动，让外面的singlescrollview来滚动
                    physics:const NeverScrollableScrollPhysics(),
                    shrinkWrap: true, //收缩，让元素宽度自适应
                  )
              );
          }),
    )
    ;



  }
  buildWateFall1() {
    TokenController tokenController = Get.find();

    ImageDetailVideoController imageDetailVideoController = Get.find<ImageDetailVideoController>();
    return ChangeNotifierProvider(
      create: (context) => TagsDetailListModel1(),
      child: Consumer<TagsDetailListModel1>(
          builder: (context, viewModel, child) {
            return
              CustomRefresh(
                  isMaterialHeader:true,
                  controller: viewModel.refreshController,
                  enablePullUp: true,
                  enablePullDown: true,
                  onRefresh: () async {
                    viewModel.onRefresh();
                  },
                  onLoading: () async {
                    viewModel.onLoading();
                  },
                  child:MasonryGridView.count(
                    padding: EdgeInsets.all(0),
                    // 展示几列
                    crossAxisCount: 2,
                    // 元素总个数
                    itemCount: viewModel.datas.length,
                    // 单个子元素
                    itemBuilder: (BuildContext context, int index) {
                      TagItem trendEntity = viewModel.datas[index];
                      // var imgsUrl = jsonDecode(trendEntity.imgsUrl as String);
                      return GestureDetector(
                        onTap: () async {

                          HudUtil.showBeautiful(context);
                          String uid = await tokenController.getUid();
                          Map<String,dynamic> params = {
                            "mid":trendEntity!.id,
                            "uid": uid
                          };
                          HttpManager.getInstance().request(url: '/platform/browseRecord/addBrowseRecord',method: Method.post,params: params);
                          imageDetailVideoController.imageDetailId.value = trendEntity!.id!;
                          await imageDetailVideoController.getImageVideoDetail();
                          HudUtil.dismiss();
                          Get.toNamed("/ui/home/imageVideoDetail");

                        },
                        child: Card(
                          margin: EdgeInsets.all(1.5),

                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(4.0),
                            child:  Column(
                              children: [
                                FancyShimmerImage(
                                  height: getRandomHeight(),
                                  imageUrl: trendEntity.cover!,
                                ),

                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [

                                    Flexible(

                                      child: Text(
                                        trendEntity.content as String,maxLines: 2,softWrap: true, // 允许文本在超出最大行数时以省略号结束
                                        overflow: TextOverflow.ellipsis, style: TextStyle(fontWeight: FontWeight.w400),// 设置文本左对齐
                                      ),

                                    ),




                                  ],
                                )

                                ,
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    Row(
                                      children: [
                                        ClipOval(
                                            child: FancyShimmerImage(imageUrl: trendEntity.avatar as String,width: 20,height: 20,)
                                        ),

                                        Text(trendEntity.username as String),
                                      ],
                                    ),
                                    Row(
                                      children: [
                                        Icon(
                                          CupertinoIcons.heart,size: 14,
                                          color: Colors.grey,),
                                        Text(trendEntity.agreeCount as String)
                                      ],
                                    )
                                  ],
                                )

                              ],
                            ),
                          ),
                        ),
                      );
                    },

                    // 纵向元素间距
                    mainAxisSpacing: 0,
                    // 横向元素间距
                    crossAxisSpacing: 0,
                    //本身不滚动，让外面的singlescrollview来滚动
                    physics:const NeverScrollableScrollPhysics(),
                    shrinkWrap: true, //收缩，让元素宽度自适应
                  )
              );
          }),
    )
    ;



  }

}
class CategoryItem {
  String id;
  String? creator;
  String? createDate;
  String count;
  String name;
  String? sort;

  CategoryItem({
    required this.id,
    this.creator,
    this.createDate,
    required this.count,
    required this.name,
    this.sort,
  });

  factory CategoryItem.fromJson(Map<String, dynamic> json) {
    return CategoryItem(
      id: json['id'],
      creator: json['creator'],
      createDate: json['createDate'],
      count: json['count'],
      name: json['name'],
      sort: json['sort'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'creator': creator,
      'createDate': createDate,
      'count': count,
      'name': name,
      'sort': sort,
    };
  }
}
